package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.mapper.TbRoleMapper;
import com.bwie.mapper.TbUserMapper;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.management.relation.Role;
import java.util.concurrent.TimeUnit;

@Service
public class TbUserServiceImpl implements TbUserService {
    @Resource
    TbUserMapper tbUserMapper;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    TbRoleMapper tbRoleMapper;
    @Override
    public R login(LoginInfoVo loginInfoVo) {
        TbUser tbUser = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserName, loginInfoVo.getUserName()));
        if(tbUser == null){
            return R.ERROR(500,"用户名不存在");
        }
        if(!tbUser.getUserPass().equals(loginInfoVo.getUserPass())){
            return R.ERROR(500,"密码错误");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("nickName", tbUser.getNickName())
                .compact();
        String tokenKey = "token-"+tbUser.getUserId();
        stringRedisTemplate.opsForValue().set(tokenKey,token,16, TimeUnit.MINUTES);
        tbUser.setUserPass(null);
        tbUser.setToken(token);
      String role =  tbRoleMapper.selectByUserId(tbUser.getUserId());
      tbUser.setRole(role);
        return R.OK(tbUser);
    }
}
